package com.wanghlme.exercise05.web;

import com.wanghlme.exercise05.pojo.Emp;
import com.wanghlme.exercise05.service.IEmpService;
import com.wanghlme.exercise05.service.impl.EmpServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginAction extends HttpServlet {
    private IEmpService empService;

    public LoginAction() {
        empService = new EmpServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String un = req.getParameter("uname");
        String up = req.getParameter("upass");
        Emp emp = empService.queryEmpByLogin(un, up);
        if (emp != null) {
            HttpSession session = req.getSession();
            session.setAttribute("emp", emp);
            List<Emp> list = empService.listAllEmployee();
            req.setAttribute("empList", list);
            this.getServletContext().getRequestDispatcher("/toMain").forward(req, resp);
        } else {
            req.setAttribute("msg", "用户名或密码错误");
            this.getServletContext().getRequestDispatcher("/page/login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
